<template>
  <div>
    <div class="df jc-sb title-btn">
      <div> <el-input v-model="search_inp" @keydown.enter="search_click" placeholder="输入任意字段进行模糊查询" class="input-with-select">
          <template #append>
            <el-button @click="search_click" :icon="Search" />
          </template>
        </el-input>
      </div>
      <el-button type="primary" @click="shop_code_into">添加商品码</el-button>
    </div>
    <el-table border :data="tableData" style="width: 100%;margin-top: 15px;">
      <el-table-column prop="GoodsID" label="商品ID" width="80" />.
      <el-table-column prop="GoodCardID" label="商品码" width="90" />
      <el-table-column prop="IDCard" label="身份证号" width="170" />
      <el-table-column prop="GoodsMoney" label="价格" width="80" />
      <el-table-column prop="GoodsName" label="商品名称" width="100" />
      <el-table-column prop="GoodsCount" label="商品数量" width="100" />
      <el-table-column prop="GoodsCreateTime" label="创建时间" width="170" />
      <el-table-column prop="GoodsUseTime" label="使用时间" width="170">
        <template #default="scope">
          {{  scope.row.GoodsUseTime || '-'}}
        </template>
      </el-table-column>
      <el-table-column prop="BarName" label="兑换网吧名称">
        <template #default="scope">
          <el-tooltip class="box-item" effect="dark" :content="scope.row.BarName" placement="top-start">
            <p class="ov1"> {{scope.row.BarName || '-'}}</p>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="AgentUserName" label="兑代理用户名">
        <template #default="scope">
          <!-- {{  scope.row.AgentUserName || '-'}}  -->
          <el-tooltip class="box-item" effect="dark" :content="scope.row.AgentUserName" placement="top-start">
            <p class="ov1"> {{scope.row.AgentUserName || '-'}}</p>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="" label="操作" width="180">
        <template #default="scope">
          <el-button @click="shop_code_edit(scope.row)" link type="primary">修改</el-button>
          <el-popconfirm title="不在考虑一下?" confirm-button-text="确定" cancel-button-text="取消" @confirm="shop_code_del(scope.row)">
            <template #reference>
              <el-button link type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <Pagination style="margin-top: 10px;" :total="total" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange"></Pagination>

    <!-- 弹框 -->
    <el-dialog v-model="dialogVisible" title="提示" width="40%">
      <el-form ref="ruleFormRef" :model="from" label-width="120px" :rules="rules" class="demo-ruleForm" style="padding-right: 25px;" status-icon>
        <el-form-item label="商品ID" prop="GoodsID">
          <el-input v-model="from.GoodsID" />
        </el-form-item>
        <el-form-item label="商品码" prop="GoodCardID">
          <div class="df w100">
            <el-input style="width: 100%;margin-right: 15px;" placeholder="点击右侧获取商品码" disabled v-model="from.GoodCardID" />
            <el-button type="primary" @click="get_shopcode" :disabled="is_add_edit=='edit'">获取</el-button>
          </div>
        </el-form-item>
        <el-form-item label="身份证号" prop="IDCard">
          <el-input v-model="from.IDCard" />
        </el-form-item>
        <el-form-item label="价格" prop="GoodsMoney">
          <el-input v-model="from.GoodsMoney" />
        </el-form-item>

        <el-form-item label="商品名称" prop="GoodsName">
          <el-input v-model="from.GoodsName" />
        </el-form-item>

        <el-form-item label="商品数量" prop="GoodsCount">
          <el-input v-model="from.GoodsCount" />
        </el-form-item>

        <el-form-item label="创建时间" prop="GoodsCreateTime">
          <el-input v-model="from.GoodsCreateTime" disabled />
        </el-form-item>
        <!-- <el-form-item label="使用时间" prop="GoodsUseTime">
          <el-input v-model="from.GoodsUseTime" />
        </el-form-item>
        <el-form-item label="兑换网吧名称" prop="BarName">
          <el-input v-model="from.BarName" />
        </el-form-item>
        <el-form-item label="兑代理用户名" prop="AgentUserName">
          <el-input v-model="from.AgentUserName" />
        </el-form-item> -->

      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="enter">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, reactive } from 'vue'
import http from '../../http'
import { Search } from '@element-plus/icons-vue'
import { useCounterStore } from '../../current'
import { ElMessage } from 'element-plus'
import Pagination from '../components/Pagination.vue'
import { storeToRefs } from 'pinia' // cnpm i pinia --save  2.1.3
const store = useCounterStore()
const { userInfo } = storeToRefs(store) //  数据
const { formart_sql } = store
// 表格数据
const tableData = ref([])
//弹框
const dialogVisible = ref(false)

// 添加商品码
const shop_code_into = async () => {
  from.value = {
    GoodsID: '',
    GoodCardID: '',
    IDCard: '',
    GoodsMoney: '',
    GoodsCreateTime: '',
    GoodsUseTime: '',
    BarName: '',
    AgentUserName: '',
    GoodsName: '',
    GoodsCount: 0
  }

  dialogVisible.value = true
  is_add_edit.value = 'add'
  from.value.GoodsCreateTime = time(new Date().getTime())
}

// 表单类型
interface FromType {
  GoodsID: string
  GoodCardID: string
  IDCard: string
  GoodsMoney: string
  GoodsCreateTime: string
  GoodsUseTime: string
  BarName: string
  AgentUserName: string
  GoodsName: string
  GoodsCount: string | number
}
// 表单
const from = ref<FromType>({
  GoodsID: '',
  GoodCardID: '',
  IDCard: '',
  GoodsMoney: '',
  GoodsCreateTime: '',
  GoodsUseTime: '',
  BarName: '',
  AgentUserName: '',
  GoodsName: '',
  GoodsCount: 0
})
// 表单校验
const rules = reactive({
  GoodsID: [{ required: true, message: '请输入商品ID', trigger: 'blur' }],
  GoodCardID: [{ required: true, message: '请输入商品码', trigger: 'blur' }],
  IDCard: [
    { required: true, message: '请输入身份证号码', trigger: 'blur' },
    { min: 18, max: 18, message: '身份证长度为18位数字', trigger: 'blur' }
  ],
  GoodsMoney: [{ required: true, message: '请输入金额', trigger: 'blur' }]
})
// 确认添加
const is_add_edit = ref('')
const enter = async () => {
  let params = {
    GoodsID: from.value.GoodsID,
    GoodCardID: from.value.GoodCardID,
    IDCard: from.value.IDCard,
    GoodsMoney: from.value.GoodsMoney,
    GoodsCreateTime: from.value.GoodsCreateTime,
    AgentUserName: null,
    GoodsUseTime: null,
    OwnerUserName: null,
    GoodsName: from.value.GoodsName,
    GoodsCount: from.value.GoodsCount
  }

  let reg = /^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\d|30|31)\d{3}[\dXx]$/ //身份证正则

  if (params.GoodsID == '') ElMessage.error('商品ID必填')
  else if (params.GoodCardID == '') ElMessage.error('请获取商品码')
  // else if (params.IDCard == '' || !reg.test(params.IDCard)) ElMessage.error('身份证格式错误')
  else if (!(!isNaN(parseFloat(params.GoodsMoney)) && isFinite(params.GoodsMoney)))
    ElMessage.error('请正确输入金额')
  else {
    if (is_add_edit.value == 'add') {
      const val_arr = filter_sql(params)
      let sql = `INSERT INTO goodcard (${val_arr.key_string}) VALUES(${val_arr.value_string})`
      // a406648c

      const res = await operate_sql(sql, 'userglobal')
      if (res.packageContent.packageStatus === 0) {
        ElMessage.success('添加成功')
        dialogVisible.value = false
        await get_list()
        from.value = {
          GoodsID: '',
          GoodCardID: '',
          IDCard: '',
          GoodsMoney: '',
          GoodsCreateTime: '',
          GoodsUseTime: '',
          BarName: '',
          AgentUserName: '',
          GoodsName: '',
          GoodsCount: 0
        }
      } else {
        ElMessage.error('添加失败')
      }

      console.log(res)
    } else if (is_add_edit.value == 'edit') {
      let val_sql = formart_sql({
        GoodsID: from.value.GoodsID,
        GoodCardID: from.value.GoodCardID,
        IDCard: from.value.IDCard,
        GoodsMoney: from.value.GoodsMoney,
        GoodsCreateTime: from.value.GoodsCreateTime,
        AgentUserName: from.value.AgentUserName == '' ? null : from.value.AgentUserName,
        GoodsUseTime: from.value.GoodsUseTime == '' ? null : from.value.GoodsUseTime,
        OwnerUserName: from.value.OwnerUserName == '' ? null : from.value.OwnerUserName,
        GoodsName: from.value.GoodsName,
        GoodsCount: from.value.GoodsCount
      })
      let sql = `UPDATE goodcard SET ${val_sql} WHERE GoodCardID = '${from.value.GoodCardID}'`
      const res = await operate_sql(sql, 'userglobal')
      if (res.packageContent.packageStatus === 0) {
        ElMessage.success('修改成功')
        dialogVisible.value = false
        await get_list()
      } else {
        ElMessage.error('修改失败')
      }
    }
  }
}

// 获取商品码
const get_shopcode = async () => {
  const res = await http.corsApi('/get_shopcode', 'post', {
    packID: '123456',
    packageType: 'adminCreateGoods',
    packageContent: {
      AgentUserName: userInfo.value.username,
      AgentUserPassword: userInfo.value.password
    }
  })

  console.log(res)
  if (res.packageContent.packageStatus === 0) from.value.GoodCardID = res.packageContent.packageMsg
}

// 修改
const shop_code_edit = (row: any) => {
  console.log(row)
  is_add_edit.value = 'edit'
  from.value = row

  dialogVisible.value = true
}

// 删除
const shop_code_del = async (row: any) => {
  console.log(row)

  const res = await operate_sql(
    `DELETE FROM goodcard WHERE GoodCardID = '${row.GoodCardID}'`,
    'userglobal'
  )
  console.log(res)

  if (res.packageContent.packageMsg == '成功' && res.packageContent.packageStatus === 0) {
    ElMessage.success('删除成功')
    await get_list()
  } else {
    ElMessage.error('删除失败')
  }
}

// 模糊查询
const search_inp = ref('')
const search_click = async () => {
  let sql = `SELECT goodcard.*, owneruser.BarName FROM goodcard LEFT JOIN owneruser ON goodcard.OwnerUserName = owneruser.OwnerUserName 
WHERE     goodcard.GoodsID LIKE '%${search_inp.value}%'  -- 模糊查询goodcard.id  
      OR goodcard.IDCard LIKE '%${search_inp.value}%'  -- 模糊查询goodcard.name  
      OR goodcard.GoodCardID LIKE '%${search_inp.value}%'  -- 模糊查询goodcard.name  
      OR owneruser.BarName LIKE '%${search_inp.value}%'  -- 模糊查询owneruser.BarName  
ORDER BY   
    goodcard.GoodCardID,     
    CASE WHEN goodcard.OwnerUserName IS NULL AND owneruser.OwnerUserName IS NULL THEN 1 ELSE 0 END    
LIMIT 15 OFFSET 0;`
  if (search_inp.value == '') {
    await get_list_sql(
      `SELECT goodcard.*,owneruser.BarName FROM goodcard LEFT JOIN owneruser ON goodcard.OwnerUserName = owneruser.OwnerUserName ORDER BY goodcard.GoodCardID OR (goodcard.OwnerUserName IS NULL AND owneruser.OwnerUserName IS NULL) LIMIT 15 OFFSET 0`,
      'userglobal'
    )
  } else await get_list_sql(sql, 'userglobal')
}

// 页面初始化
onMounted(async () => {
  await get_list()

  let total_arr = await get_total('SELECT COUNT(*) FROM goodcard', 'userglobal')
  total.value = Number(total_arr[0]['COUNT(*)'])
})

const get_list = async () => {
  await get_list_sql(
    `SELECT goodcard.*,owneruser.BarName FROM goodcard LEFT JOIN owneruser ON goodcard.OwnerUserName = owneruser.OwnerUserName ORDER BY goodcard.GoodCardID OR (goodcard.OwnerUserName IS NULL AND owneruser.OwnerUserName IS NULL) LIMIT 15 OFFSET 0`,
    'userglobal'
  )
}

const page = ref(1) //页码数
const pageSize = ref(15) //每页条数
const total = ref(10)

// 分页 
const handleSizeChange = async (val: number) => {
  console.log(`${val} items per page`)
  pageSize.value = val
  // page.value = 1
  // 每页显示的条数
  if ((page.value - 1) * pageSize.value - 1 <= 0) {
 
    await get_list_sql(
      `SELECT goodcard.*,owneruser.BarName FROM goodcard LEFT JOIN owneruser ON goodcard.OwnerUserName = owneruser.OwnerUserName ORDER BY goodcard.GoodCardID OR (goodcard.OwnerUserName IS NULL AND owneruser.OwnerUserName IS NULL) LIMIT ${pageSize.value} OFFSET 0`,
      'userglobal'
    )
  } else {
 
    await get_list_sql(
      `SELECT goodcard.*,owneruser.BarName FROM goodcard LEFT JOIN owneruser ON goodcard.OwnerUserName = owneruser.OwnerUserName ORDER BY goodcard.GoodCardID OR (goodcard.OwnerUserName IS NULL AND owneruser.OwnerUserName IS NULL) LIMIT ${
        pageSize.value
      } OFFSET ${(page.value - 1) * pageSize.value}`,
      'userglobal'
    )
  }
}
const handleCurrentChange = async (val: number) => {
  console.log(`current page: ${val}`)
  page.value = val
  // 当前页码数
  if ((val - 1) * pageSize.value - 1 <= 0) {
 
    await get_list_sql(
      `SELECT goodcard.*,owneruser.BarName FROM goodcard LEFT JOIN owneruser ON goodcard.OwnerUserName = owneruser.OwnerUserName ORDER BY goodcard.GoodCardID OR (goodcard.OwnerUserName IS NULL AND owneruser.OwnerUserName IS NULL) LIMIT ${pageSize.value} OFFSET 0`,
      'userglobal'
    )
  } else {
  
    await get_list_sql(
      `SELECT goodcard.*,owneruser.BarName FROM goodcard LEFT JOIN owneruser ON goodcard.OwnerUserName = owneruser.OwnerUserName ORDER BY goodcard.GoodCardID OR (goodcard.OwnerUserName IS NULL AND owneruser.OwnerUserName IS NULL) LIMIT ${
        pageSize.value
      } OFFSET ${(page.value - 1) * pageSize.value}`,
      'userglobal'
    )
  }
}

const get_total = async (sql, dbName) => {
  const res = await http.corsApi('/', 'post', {
    packID: '123456',
    packageType: 'adminSql',
    packageContent: {
      AgentUserName: userInfo.value.username,
      AgentUserPassword: userInfo.value.password,
      sql: sql,
      dbName: dbName
    }
  })
  console.log(res)
  return JSON.parse(res.packageContent.packageMsg)
}

// 操作数据库统一请求
const operate_sql = async (sql: string, name: string) => {
  const res = await http.corsApi('/index', 'post', {
    packID: '123456',
    packageType: 'adminSql',
    packageContent: {
      AgentUserName: userInfo.value.username,
      AgentUserPassword: userInfo.value.password,
      sql: sql,
      dbName: name
    }
  })
  console.log(res)
  let data: any = { tableData: [], res: {} }
  if (res.packageContent.packageMsg == '成功') {
    data = res
  } else {
    data = JSON.parse(res.packageContent.packageMsg)
  }
  console.log(data)

  return data
}

// 操作数据库统一请求
const get_list_sql = async (sql: string, name: string) => {
  const res = await http.corsApi('/index', 'post', {
    packID: '123456',
    packageType: 'adminSql',
    packageContent: {
      AgentUserName: userInfo.value.username,
      AgentUserPassword: userInfo.value.password,
      sql: sql,
      dbName: name
    }
  })
  console.log(res)
  if (res.packageContent.packageMsg == '成功') {
    tableData.value = []
  } else {
    tableData.value = JSON.parse(res.packageContent.packageMsg)
  }

  // return data
}

// 时间格式化
const time = (t) => {
  var dt = new Date(t)
  var y = dt.getFullYear()
  var m = dt.getMonth() + 1
  var d = dt.getDate()
  var h = dt.getHours()
  var mi = dt.getMinutes()
  var s = dt.getSeconds()

  return `${y}-${m}-${d}-${h}-${mi}-${s}`
}

// 拼接sql
const filter_sql = (data) => {
  let arr = Object.keys(data)
  let key_string = ''
  let value_string = ''
  for (var i = 0; i < arr.length; i++) {
    if (i == arr.length - 1) {
      key_string += arr[i] + ''

      if (data[arr[i]] == null) {
        value_string += `${data[arr[i]]}`
      } else {
        value_string += `'${data[arr[i]]}'`
      }
    } else {
      key_string += arr[i] + ','
      if (data[arr[i]] == null) {
        value_string += `${data[arr[i]]},`
      } else {
        value_string += `'${data[arr[i]]}',`
      }
    }
  }

  console.log(key_string)
  console.log(value_string)
  return {
    key_string,
    value_string
  }
}
</script>

<style scoped>
</style>